//
//  LunBoTuView.swift
//  约健
//
//  Created by tyh on 2017/9/14.
//  Copyright © 2017年 tyh. All rights reserved.
//

import UIKit

class LunBoTuView: UIView,UIScrollViewDelegate {
    var scr:UIScrollView?
    var timer:Timer?
    var imageNames = ["1","2","3"]
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        scr = UIScrollView.init(frame: self.bounds)
        scr?.delegate = self
        scr?.isPagingEnabled = true
        scr?.decelerationRate = 0.1
        scr?.showsVerticalScrollIndicator = false
        scr?.showsHorizontalScrollIndicator = false
        creatMyScrollView()
        creatTimer()
        self.addSubview(scr!)
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func creatMyScrollView(){
        for i in 0...(imageNames.count - 1){
            
            let imageView = UIImageView(frame: CGRect(x: self.frame.size.width * CGFloat(i), y: 0, width: self.frame.size.width, height: self.frame.size.height))
            
            imageView.image = UIImage(named: "\(imageNames[i])" + ".jpg")
            
            scr?.addSubview(imageView)
            
        }
        
        let imageView = UIImageView(frame:CGRect(x: CGFloat(imageNames.count) * self.frame.size.width, y: 0, width: self.frame.size.width, height: self.frame.size.height))
        imageView.image = UIImage(named: "\(imageNames[0])" + "jpg")
        
        scr?.addSubview(imageView)
    }
    
    func creatTimer(){
        timer = Timer.init(timeInterval: 3.0, target: self, selector: #selector(timerManger), userInfo: nil, repeats: true)
        //加入线程中
        RunLoop.current.add(timer!, forMode: .commonModes)
        
    }
    
    func timerManger(){
        
        scr?.setContentOffset(CGPoint.init(x: (scr?.contentOffset.x)! + self.frame.size.width, y: 0), animated: true)
        
        
    }
    //无限轮播
    func timerManger2(){
        if scr?.contentOffset.x == CGFloat(self.frame.size.width) * CGFloat(imageNames.count) {
            scr?.setContentOffset(CGPoint(x: 0,y: 0), animated: true)
        }
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        
        timer?.invalidate()
        timer = nil
    }
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        self.creatTimer()
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        self.timerManger2()
        
    }

    
    

}
